const { app, dialog } = require("electron");
const Store = require("electron-store");
const Types = require("../../const/eventName");

const fileStore = new Store({ name: "fileData" });
const settingStore = new Store({ name: "settings" });
// 获取文件保存位置
function getDocPath(event) {
  const savePath = settingStore.get(Types.SETTINGSAVEPATH);
  event.sender.send(
    Types.GETDOCPATHREPLY,
    savePath || app.getPath("documents")
  );
}

// 导入文件
function openFileDialog(event) {
  dialog
    .showOpenDialog({
      title: "导入文件",
      buttonLabel: "导入",
      message: "请选择要导入的md文件",
      filters: [{ name: "MD File", extensions: ["md"] }],
      properties: ["openFile", "multiSelections"],
    })
    .then((paths) => {
      event.sender.send(Types.OPENFILEDIALOGREPLY, paths);
    });
}

// 获取store存储的文件
function getFileStoreFiles(event) {
  const files = fileStore.get(Types.STOREFILES);
  event.sender.send(Types.GETFILESTOREFILESREPLY, files);
}

//保存/删除文件并持久化到store
function updateFilesToFileStore(_, data) {
  let { files, isDelete = false } = data;
  const store = fileStore.get(Types.STOREFILES) || {};
  if (!Array.isArray(files)) {
    files = [files];
  }
  files.forEach((file) => {
    const { id } = file;
    if (isDelete) {
      const { [id]: file, ...after } = store;
      fileStore.set(Types.STOREFILES, after);
    } else {
      const newFiles = { ...store, [id]: file };
      fileStore.set(Types.STOREFILES, newFiles);
    }
  });
}

module.exports = {
  getDocPath,
  openFileDialog,
  getFileStoreFiles,
  updateFilesToFileStore,
};
